﻿using AutoMapper;
using B.S.Business.Domain;
using B.S.Business.ErrorCode;
using B.S.Business.Infacetrue;
using MediatR;

namespace B.S.Business.Read.API.Applications
{
    public class PurchaseQueryCommandHandler : IRequestHandler<PurchaseQueryCommand, ApiPaging<Purchase>>
    {
        private readonly IBaseRepository<Purchase> purchaseRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="purchaseRepo"></param>
        /// <param name="mapper"></param>
        public PurchaseQueryCommandHandler(IBaseRepository<Purchase> purchaseRepo, IMapper mapper)
        {
            this.purchaseRepo = purchaseRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回</returns>
        public Task<ApiPaging<Purchase>> Handle(PurchaseQueryCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<Purchase> result = new ApiPaging<Purchase>();
            // 查询
            var linq = purchaseRepo.GetAll().Where(x => x.IsDeleted == false);

            // 修正条件判断，当输入不为空时进行过滤
            if (!string.IsNullOrEmpty(request.Productcode))
            {
                linq = linq.Where(x => x.Productcode == request.Productcode);
            }
            if (!string.IsNullOrEmpty(request.ProductName))
            {
                linq = linq.Where(x => x.ProductName.Contains(request.ProductName));
            }

            // 分页
            result.TotalCount = linq.Count();
            result.PageCount = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            result.Lists = linq.OrderByDescending(x => x.PurchaseId)
                               .Skip((request.PageIndex - 1) * request.PageSize)
                               .Take(request.PageSize)
                               .ToList();

            // 返回
            return Task.FromResult(result);
        }
    }
}